#include "captureCallBack.h"
#include "DeckLinkAPI.h"

#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <stdlib.h>



#include <fcntl.h>


using namespace std;

void CaptureCallback::dPrint(string data)
{

	string output="[CaptureCallback] " + data;

//	cout << output << endl;
};


CaptureCallback::CaptureCallback()
{
	dPrint("INIT");
	once=false;
	count=0;
//	outputFile.open("test.wav",fstream::in | fstream::out | fstream::binary | fstream::app );


//	audioOutputFile = open("audio.raw", O_WRONLY|O_CREAT|O_TRUNC, 0664);
};



HRESULT CaptureCallback::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
{
	if (!once)
	{

		/*	
		count++;
		if (count==200)
		{
			once=true;
			dPrint("DONE");
		}
		*/
		
		if (videoFrame)
		{
		
			int length=videoFrame->GetRowBytes()*videoFrame->GetHeight();
		
			char *frameBytes;
			videoFrame->GetBytes((void **)&frameBytes);
	
			cout.write(frameBytes,length);
	

			dPrint("video");
			

			
		}
		
		
		if (audioFrame)
		{
						
			int length=audioFrame->GetSampleFrameCount() * 2 * (16 /8);
			char *audioframeBytes;
			audioFrame->GetBytes((void **)&audioframeBytes);
			
			/*
			string s;
			stringstream out; 
			//out << length; //1843200
			out << strlen(audioframeBytes); //1920000
			//out << videoFrame->GetRowBytes(); //2560
			s = out.str();
			int number=atoi(s.c_str());
			*/

			//cout.write(audioframeBytes,length);
			
			cerr.write(audioframeBytes,length);
			
		}

		
		
	}

};


ULONG CaptureCallback::AddRef(void)
{
	return 0;
};


ULONG CaptureCallback::Release(void)
{
	return 0;
};


HRESULT CaptureCallback::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags)
{
	return S_OK;
};
	
